<template>
  <div>
    <el-dialog
      :title="projectFormData.id === 0 ? '新增项目' : '编辑项目'"
      v-model="isShowProjectDialog"
      width="30%"
    >
      <el-form
        :model="projectFormData"
        ref="projectForm"
        :rules="projectRules"
        label-width="100px"
        :inline="false"
        size="default"
      >
        <el-form-item label="项目名" prop="name">
          <el-input v-model="projectFormData.name" clearable></el-input>
        </el-form-item>
        <!-- 自动化类型只有web和api两种，所以用单选框就好 -->
        <el-form-item label="描述信息" prop="desc">
          <el-input v-model="projectFormData.proDesc" clearable></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="isShowProjectDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="projectFormData.id === 0 ? addProject() : updateProject()"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-row>
      <el-col :span="5">
        <el-card
          shadow="always"
          :body-style="{
            padding: '20px',
            'overflow-y': 'auto',
            height: 'calc(100vh - 170px)',
          }"
        >
          <template #header>
            <el-row>
              <el-col :span="12"
                ><span class="card-title">项目列表</span></el-col
              >
              <el-col :span="12" style="text-align: right">
                <el-button
                  type="success"
                  size="default"
                  :icon="Plus"
                  @click="openProjectAdder"
                  >新增</el-button
                ></el-col
              >
            </el-row>
          </template>
          <ProjectCard
            v-for="sunnyProject in projectList"
            :key="sunnyProject.id"
            :project="sunnyProject"
            :class="{
              'selected-project':
                sunnyProject.id === projectStore.selectedProject.id,
            }"
            @operate="operateProject($event, sunnyProject)"
            @click="selectProject(sunnyProject)"
          ></ProjectCard>
        </el-card>
      </el-col>
      <el-col :span="19">
        <RouterView name="module"> </RouterView>
        <RouterView name="variable"> </RouterView>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import type { SunnyProject } from "@/types/sunnyProject/type";
import ProjectCard from "./ProjectCard.vue";
import { ref, onMounted } from "vue";
import {
  addProjectApi,
  deleteProjectApi,
  listProjectsApi,
  updateProjectApi,
} from "@/api/sunnyproject";
import {
  ElMessage,
  type FormRules,
  type FormInstance,
  ElMessageBox,
} from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useProjectStore } from "@/stores/sunnyProjectStore";
import { onBeforeRouteUpdate } from "vue-router";
import router from "@/router";
import { storeToRefs } from "pinia";

const projectStore = useProjectStore();

const { projectList } = storeToRefs(projectStore);

onMounted(() => {
  listProjects();
});

onBeforeRouteUpdate(() => {
  listProjects();
});

/**
 * 获取project列表
 */
function listProjects() {
  listProjectsApi()
    .then(({ data }) => {
      projectList.value = data;
      //选中已选中的模块或者默认的  请选择模块 的模块
      if (projectList.value.length > 0) {
        // if (projectStore.selectedProject.id !== -1) {
        selectProject(projectStore.selectedProject);
        // }
      }
    })
    .catch(() => {
      ElMessage.error("获取请求列表信息失败");
    });
}

const isShowProjectDialog = ref(false);

/**
 * 打开新增、编辑窗口
 */
function openProjectAdder() {
  //重置新增项目的信息
  projectFormData.value = {
    id: 0,
    name: "",
    proDesc: "",
    stepCount: 0,
    caseCount: 0,
    moduleList: "",
  };
  //打开新增窗口
  isShowProjectDialog.value = true;
}

/**初始化的新增模板 */
const projectFormData = ref<SunnyProject>({
  id: 0,
  name: "",
  proDesc: "",
  stepCount: 0,
  caseCount: 0,
  moduleList: "",
});

const projectForm = ref<FormInstance>();
const projectRules = ref<FormRules>({
  name: [
    { required: true, message: "项目名必填", trigger: "blur" },
    {
      min: 2,
      max: 15,
      message: "项目名称请限制在2到15位之间",
      trigger: "blur",
    },
  ],
  desc: {
    max: 100,
    message: "描述信息请不要超过100位",
    trigger: "blur",
  },
});

/**
 * 完成项目新增请求
 */
function addProject() {
  isShowProjectDialog.value = false;
  addProjectApi(projectFormData.value)
    .then(({ data }) => {
      ElMessage.success("新增项目" + data.name + "成功");
    })
    .catch(() => {
      ElMessage.error("新增项目失败");
    })
    .then(() => {
      listProjects();
    });
}

/**
 * 完成项目更新请求
 */
function updateProject() {
  isShowProjectDialog.value = false;
  updateProjectApi(projectFormData.value)
    .then(() => {
      ElMessage.success("更新项目信息成功");
    })
    .then(() => {
      listProjects();
    });
}

function selectProject(sunnyProject: SunnyProject) {
  projectStore.selectedProject = sunnyProject;
  router.replace({
    name: "infoOfProject",
    params: { projectId: sunnyProject.id },
  });
}

function operateProject(type: string, sunnyProject: SunnyProject) {
  switch (type) {
    case "edit":
      editProject(sunnyProject);
      break;
    case "delete":
      deleteProject(sunnyProject);
      break;
    case "run":
      runProject(sunnyProject);
      break;
    case "result":
      viewResutOfProject(sunnyProject);
      break;
  }
}

/**打开编辑窗口 */
function editProject(sunnyProject: SunnyProject) {
  projectFormData.value = sunnyProject;
  isShowProjectDialog.value = true;
}

function deleteProject(sunnyProject: SunnyProject) {
  ElMessageBox.confirm(`确定要删除${sunnyProject.name}吗？`)
    .then(() => {
      deleteProjectApi(sunnyProject.id)
        .then(() => {
          ElMessage.success("删除成功");
        })
        .catch(() => {
          ElMessage.error(`删除项目${sunnyProject.name}失败`);
        })
        .then(() => {
          if (sunnyProject.id === projectStore.selectedProject.id) {
            projectStore.selectedProject = {
              id: -1,
              name: "请选择项目",
              proDesc: "",
              stepCount: 0,
              caseCount: 0,
              moduleList: "",
            };
          }
          listProjects();
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
}

function runProject(sunnyProject: SunnyProject) {
  console.log("点击了运行按钮");
  projectStore.selectedProject = sunnyProject;
  router.push({ name: "run" });
}

function viewResutOfProject(sunnyProject: SunnyProject) {
  //选中当前的project
  projectStore.selectedProject = sunnyProject;
  router.push({
    name: "resultOfProject",
    params: { projectId: sunnyProject.id },
  });
}
</script>

<style scoped>
.el-col {
  padding: 2px 5px;
}

.selected-project {
  background-color: #a0cfff;
}
</style>
